package com.xkdx.guangguang.fragment.comment;

import java.io.IOException;
import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.weibo.sdk.android.Oauth2AccessToken;
import com.weibo.sdk.android.Weibo;
import com.weibo.sdk.android.WeiboAuthListener;
import com.weibo.sdk.android.WeiboDialogError;
import com.weibo.sdk.android.WeiboException;
import com.weibo.sdk.android.api.UsersAPI;
import com.weibo.sdk.android.keep.AccessTokenKeeper;
import com.weibo.sdk.android.net.RequestListener;
import com.weibo.sdk.android.sso.SsoHandler;
import com.xkdx.caipiao.R;
import com.xkdx.guangguang.ManagerActivity;
import com.xkdx.guangguang.fragment.BaseFragment;
import com.xkdx.guangguang.fragment.comment.BindSinaModule.BindUser;
import com.xkdx.guangguang.module.network.AbsModule;
import com.xkdx.guangguang.module.statics.IConstants;
import com.xkdx.guangguang.util.SharePrefenceUtil;

public class BrandCommentFragment extends BaseFragment implements
		OnClickListener {
	View view;

	private String ShopID, Flag, BrandID;
	private LayoutInflater inflater;
	private EditText ed_shopCommentInfos;
	private Button btn_back, btn_commit;
	private ProgressDialog pd = null;
	private ImageView sinaShare;
	// private boolean sinaFlag = true;
	public static Oauth2AccessToken AccessToken;
	public static Oauth2AccessToken AccessTokenbindsina;
	public static final int comminfoNum = 140;
	private String ShopName = "";
	private String BrandName = "";
	private String startTag;
	private StringBuffer buff;

	/**
	 * 绑定新浪微博所需变量
	 */
	private String bindSinaToken;
	private String bindSinaWeiboExpireTime;
	private String bindSinaUserID;
	private SsoHandler mSsoHandler;
	private Weibo sinaWeibo;
	private String uid;
	public String sinaWeiboToken;
	public String sinaWeiboExpireTime;
	public long SinaWeiboUserID; // 新浪微博用户id
	public String UserNickName; // 用户昵称
	public String UserSex = "-1"; // 用户性别

	BrandCommentAction commentAction;
	BrandCommetnModule commentModule;
	BrandCommentPresistence commentPresistence;

	// 绑定新浪微博
	BindSinaAction bindSinaAction;
	BindSinaModule bindSinaModule;
	BindSinaPresistence bindSinaPresistence;
	BindUser bindUser;

	SharePrefenceUtil sinaSP;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		buff = new StringBuffer();
		BrandID = getArguments().getString("BrandID");
		BrandName = getArguments().getString("BrandName");
		inflater = LayoutInflater.from(getActivity());

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		IConstants.isCommitSuccess = false;
		sinaSP = new SharePrefenceUtil(getActivity(), IConstants.SP_USER);
		view = inflater
				.inflate(R.layout.shop_commentaryinfos, container, false);
		findView();
		setOnClick();

		return view;
	}

	@Override
	public void findView() {

		ed_shopCommentInfos = (EditText) view
				.findViewById(R.id.et_commentaryinfos);
		sinaShare = (ImageView) view.findViewById(R.id.iv_sinacommentaryinfos);
		btn_back = (Button) view.findViewById(R.id.btn_commentback);
		btn_commit = (Button) view.findViewById(R.id.btn_commentcommit);

		/**
		 * 设置新浪图标默认状态
		 */

		bindSinaToken = sinaSP.getSinaWeiboToken();
		bindSinaWeiboExpireTime = sinaSP.getSinaWeiboExpireTime();
		bindSinaUserID = sinaSP.getUserID();
		if (!"".equals(bindSinaToken) && (!"".equals(bindSinaUserID))) {
			sinaShare.setImageResource(R.drawable.sinacommtary);
		} else {
			sinaShare.setImageResource(R.drawable.sinauncommtary);
		}
		commentModule = new BrandCommetnModule();

	}

	@Override
	public void onResume() {
		super.onResume();
		bindSinaToken = sinaSP.getSinaWeiboToken();
		bindSinaWeiboExpireTime = sinaSP.getSinaWeiboExpireTime();
		bindSinaUserID = sinaSP.getUserID();
		if (!"".equals(bindSinaToken) && (!"".equals(bindSinaUserID))) {
			sinaShare.setImageResource(R.drawable.sinacommtary);
		} else {
			sinaShare.setImageResource(R.drawable.sinauncommtary);
		}
	}

	@Override
	public void setOnClick() {
		btn_back.setOnClickListener(this);
		btn_commit.setOnClickListener(this);
		sinaShare.setOnClickListener(this);

		// 限制评论字数
		ed_shopCommentInfos.addTextChangedListener(new TextWatcher() {

			@Override
			public void afterTextChanged(Editable s) {
				if ("shop".equals(Flag)) {
					startTag = "@" + ShopName + ":";
				} else {
					startTag = "@" + BrandName + ":";
				}

				int charablenum = comminfoNum - startTag.length()
						- ed_shopCommentInfos.getText().length();
				if (charablenum <= 0) {
					Toast.makeText(getActivity(), "评论内容超出140字,无法继续评论!",
							Toast.LENGTH_SHORT).show();
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}
		});

	}

	@Override
	public void showLoading() {
		dataLoadDialog.show();
		IConstants.hideInputMethodAways(getActivity(), view);
		SharePrefenceUtil su = new SharePrefenceUtil(getActivity(),
				IConstants.SP_USER);
		commentAction = new BrandCommentAction(su.getUserID(), BrandID,
				su.getUserLoginToken(), ed_shopCommentInfos.getText()
						.toString());
		commentPresistence = new BrandCommentPresistence(this);
		((ManagerActivity) getActivity()).addCurrentTask(commentPresistence);
		commentPresistence.setActitons(commentAction);
		commentPresistence.setModule(commentModule);
		commentPresistence.execute();
		dataLoadDialog.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				if (commentPresistence != null) {
					commentPresistence.cancel(true);
				}
				getFragmentManager().popBackStack();

			}
		});
		dataLoadDialog.show();

	}

	@Override
	public void showLoaded(HashMap<String, AbsModule> map) {
		dataLoadDialog.dismiss();
		if (map.containsKey("0")) {
			if (commentModule.isCommentSucess) {
				IConstants.isCommitSuccess = true;
				Toast.makeText(getActivity(), "评论成功", Toast.LENGTH_SHORT)
						.show();
				getFragmentManager().popBackStack();
			} else {
				IConstants.isCommitSuccess = false;
				Toast.makeText(getActivity(), "请重新登录", Toast.LENGTH_SHORT)
						.show();
			}
		} else {
			IConstants.isCommitSuccess = false;
			refresh(map);
		}
	}

	@Override
	public void showClick(HashMap<String, AbsModule> map) {
		dataLoadDialog.dismiss();
		if (map.containsKey("0")) {
			bindUser = bindSinaModule.bindUser;
			setSinaBind();
		} else {
			showErrorTip(map);
		}

	}

	private void setSinaBind() {
		InputMethodManager im = (InputMethodManager) getActivity()
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		if (im.isActive()) {
			im.hideSoftInputFromWindow(ed_shopCommentInfos.getWindowToken(), 0);
		}
		Toast.makeText(getActivity(), "新浪微博绑定成功", Toast.LENGTH_SHORT).show();
		sinaShare.setImageResource(R.drawable.sinacommtary);

		bindSinaToken = sinaSP.getSinaWeiboToken();
		bindSinaWeiboExpireTime = sinaSP.getSinaWeiboExpireTime();
		bindSinaUserID = sinaSP.getUserID();

	}

	@Override
	public void showLoadMore(HashMap<String, AbsModule> map) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_commentback:
			IConstants.hideInputMethodAways(getActivity(), view);
			getFragmentManager().popBackStack();
			break;
		case R.id.btn_commentcommit: // 提交按钮
			SharePrefenceUtil su = new SharePrefenceUtil(getActivity(),
					IConstants.SP_USER);
			String loginToken = su.getUserLoginToken();
			if (!loginToken.equals("")) {
				String commentaryInfos = ed_shopCommentInfos.getText()
						.toString();
				if (TextUtils.isEmpty(commentaryInfos)) {
					Toast.makeText(getActivity(), "您还没有进行评论,请输入评论内容!",
							Toast.LENGTH_SHORT).show();
				} else {
					showLoading();
				}
			} else {
				UserLogin();
			}
			break;
		case R.id.iv_sinacommentaryinfos:
			SinaImageChange();
			break;
		default:
			break;
		}

	}

	/**
	 * 绑定新浪微博
	 */
	private void SinaImageChange() {
		if (!"".equals(bindSinaToken) && (!"".equals(bindSinaUserID))) {
			// unBindSina(); // 解除绑定
		} else {
			bindSinaPresistence = new BindSinaPresistence(this);
			BindSina(); // 绑定新浪微博
		}
	}

	private void BindSina() {
		IConstants.LoginWhich = 6;
		sinaWeibo = Weibo.getInstance(IConstants.CONSUMER_KEY,
				IConstants.REDIRECT_URL);
		try {
			Class sso = Class.forName("com.weibo.sdk.android.sso.SsoHandler");
			mSsoHandler = new SsoHandler(getActivity(), sinaWeibo);
			mSsoHandler.authorize(new AuthDialogListener());

		} catch (ClassNotFoundException e) {
			sinaWeibo.authorize(getActivity(), new AuthDialogListener());
		}
	}

	/**
	 * 处理新浪绑定
	 */
	class AuthDialogListener implements WeiboAuthListener {

		@Override
		public void onComplete(Bundle values) {

			String token = values.getString("access_token");
			String expires_in = values.getString("expires_in");
			uid = values.getString("uid");
			sinaWeiboToken = token; // 新浪微博token
			sinaWeiboExpireTime = expires_in;
			AccessTokenbindsina = new Oauth2AccessToken(token, expires_in);

			if (AccessTokenbindsina.isSessionValid()) {
				try {
					Class sso = Class
							.forName("com.weibo.sdk.android.api.WeiboAPI");// 如果支持weiboapi的话，显示api功能演示入口按钮
				} catch (ClassNotFoundException e) {
					// Log.i("log","未找到api");
				}
				AccessTokenKeeper.keepAccessToken(getActivity(),
						AccessTokenbindsina);
				uploadSinaInfo();

			}
		}

		@Override
		public void onError(WeiboDialogError e) {

		}

		@Override
		public void onCancel() {

		}

		@Override
		public void onWeiboException(WeiboException e) {

		}

	}

	private void uploadSinaInfo() {
		if (Long.parseLong(uid) > 0) {
			SinaWeiboUserID = Long.parseLong(uid);
			UsersAPI user = new UsersAPI(AccessTokenbindsina);
			user.show(SinaWeiboUserID, new RequestListener() {
				@Override
				public void onIOException(IOException e) {
				}

				@Override
				public void onError(WeiboException e) {
				}

				@Override
				public void onComplete(String response) {

					JSONObject userObject;
					try {
						userObject = new JSONObject(response);
						UserNickName = userObject.getString("screen_name");
						UserSex = (String) userObject.getString("gender");
						if ("m".equals(UserSex)) {
							UserSex = "0";
						} else if ("f".equals(UserSex)) {
							UserSex = "1";
						} else {
							UserSex = "-1";
						}

						// sendBindSInaMessage(); // 上传新浪微博信息

					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			});
			sendBindSInaMessage();
		}
	}

	/**
	 * 上传新浪微博信息
	 */
	protected void sendBindSInaMessage() {
		SharePrefenceUtil su = new SharePrefenceUtil(getActivity(),
				IConstants.SP_USER);
		bindSinaAction = new BindSinaAction(su.getUserID(),
				su.getUserLoginToken(), String.valueOf(SinaWeiboUserID),
				UserNickName, UserSex, sinaWeiboToken, sinaWeiboExpireTime);
		bindSinaModule = new BindSinaModule(getActivity());

		((ManagerActivity) getActivity()).addCurrentTask(bindSinaPresistence);
		bindSinaPresistence.setActitons(bindSinaAction);
		bindSinaPresistence.setModule(bindSinaModule);
		bindSinaPresistence.execute();
	}

	public SsoHandler GetBindSsoHandler() {
		return mSsoHandler;
	}
	
}
